//
//  ShareViewController.m
//  e蜂通信
//
//  Created by 李旭 on 16/5/9.
//  Copyright © 2016年 wanzhao. All rights reserved.
//

#import "ShareViewController.h"
#import "CContactModel.h"
#import "CContactMgr.h"
#import "CAccountModel.h"
#import "CAccountMgr.h"
#import "CFolderMgr.h"
#import "FMShareDataBase.h"
#import "EFengShare.h"
#import "AFNetworking.h"
#import "NSString+MD5Addition.h"
#import "NSString+DESAndBase64.h"
#import "ContactViewController.h"

@interface ShareViewController ()
@property (nonatomic,strong)NSMutableArray *imageArray;
@property (nonatomic,copy)NSString *text;
@end

@implementation ShareViewController

-(NSMutableArray *)imageArray
{
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    UINavigationItem *item = self.navigationController.navigationBar.topItem;
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(0, 0, 100, 44);
    label.text = @"e蜂通信";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor blackColor];
    label.font = [UIFont boldSystemFontOfSize:18.0f];
    item.titleView = label;
    item.rightBarButtonItem = nil;
    self.navigationController.view.backgroundColor = [UIColor whiteColor];
    [self fetchItemDataAtBackground];
    

}
- (BOOL)isContentValid {
    // Do validation of contentText and/or NSExtensionContext attachments here
    self.charactersRemaining = @(50 - self.contentText.length);
    return YES;
    
}
//- (UIView *)loadPreviewView
//{
////    CGFloat width = self.textView.bounds.size.width;
////    CGFloat heigh = self.textView.bounds.size.height;
////    if (_imageArray.count>0) {
////        UIScrollView *imageScrollview = [[UIScrollView alloc]initWithFrame:self.textView.bounds];
////        imageScrollview.contentSize = CGSizeMake(_imageArray.count * width, heigh);
////        imageScrollview.pagingEnabled = YES;
////        for (NSInteger i = 0 ; i < _imageArray.count; i++) {
////            UIImageView *imageView = [[UIImageView alloc]initWithImage:_imageArray[i]];
////            imageView.frame = CGRectMake(i*width, 0, width, heigh);
////            [imageScrollview addSubview:imageView];
////        }
////        [self.textView.superview.superview addSubview:imageScrollview];
////        [self.textView removeFromSuperview];
////    }
//    if (self.text.length > 0) {
//        self.textView.text = [self.textView.text stringByAppendingString:self.text];
//    }
//    return nil;
//}
- (void)didSelectPost {
    // This is called after the user selects Post. Do the upload of contentText and/or NSExtensionContext attachments.
    
    // Inform the host that we're done, so it un-blocks its UI. Note: Alternatively you could call super's -didSelectPost, which will similarly complete the extension context.
    [self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}

- (NSArray *)configurationItems {
    // To add configuration options via table cells at the bottom of the sheet, return an array of SLComposeSheetConfigurationItem here.
//    SLComposeSheetConfigurationItem *item1 = [[SLComposeSheetConfigurationItem alloc] init];
//    item1.title = @"分享给同事";
//    item1.tapHandler = ^{
//        ContactViewController *vc = [[ContactViewController alloc]init];
//        vc.navigationItem.title = @"发送至";
//
//        vc.view.backgroundColor = [UIColor greenColor];
//        vc.preferredContentSize = CGSizeMake(vc.view.frame.size.width, self.view.bounds.size.height - 150);
//        [self pushConfigurationViewController:vc];
//    };
    SLComposeSheetConfigurationItem *item2 = [[SLComposeSheetConfigurationItem alloc] init];
    item2.title = @"分享到e蜂圈";
    item2.tapHandler = ^{
        
          UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"发送至工作圈?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sendshare];
        }];
        
        UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
           [self didSelectCancel];
            
        }];
        [alert addAction:actionNo];
        [alert addAction:actionYes];
        [self presentViewController:alert animated:YES completion:nil];
                                    
        
    };
    
    return @[item2];
}

-(void)fetchItemDataAtBackground
{
    //后台获取
    [self.imageArray removeAllObjects];
    self.text = nil;
        NSArray *inputItems = self.extensionContext.inputItems;
        NSExtensionItem *item = inputItems.firstObject;//无论多少数据，实际上只有一个NSExtensionItem 对象
        for (NSItemProvider *provider in item.attachments) {
            //completionHandler 是异步运行的
            
            NSString *dataType = provider.registeredTypeIdentifiers.firstObject;//实际上一个NSItemProvider里也只有一种数据类型
            if ([dataType isEqualToString:@"public.jpeg"]) {
                [provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(UIImage *image, NSError *error){
                    [self.imageArray addObject:image];
                }];
                
            }else if ([dataType isEqualToString:@"public.plain-text"]){
                [provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(NSString *contentText, NSError *error){
                    self.text = contentText;
                }];
            }else if ([dataType isEqualToString:@"public.url"]){
                [provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(NSURL *url, NSError *error){
                    self.text = url.absoluteString;
                }];
            }else if ([dataType isEqualToString:@"public.png"]){
                [provider loadItemForTypeIdentifier:dataType options:nil completionHandler:^(UIImage *image, NSError *error){
                    [self.imageArray addObject:image];
                }];
            }else
                NSLog(@"don't support data type: %@", dataType);
        }
}
-(void)sendshare
{
    __weak typeof (self) weakself = self;
    if (self.text.length > 0) {
        self.textView.text = [self.textView.text stringByAppendingString:self.text];
    }
    [[FMShareDataBase shareDataBase] updateCompanyQueue];
    [[FMShareDataBase shareDataBase] updatePersonalQueue];
    CAccountModel *model = [[CFolderMgr shareInstance].accMgr getRecentlyLoginAccount];
    CContactModel *contact = [[[CContactMgr alloc] init] loadContactWithUserCode:model.userName];
    NSString *type = nil;
    if (self.imageArray.count > 0 && self.contentText.length <= 0) {
        type = @"img";
    } else if (self.imageArray.count > 0 && self.contentText.length > 0){
        type = @"textimg";
    } else {
        type = @"text";
    }
    CServerSettingModel *serverSetting = [[CFolderMgr shareInstance].serSettingMgr getSetting];
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] *1000 + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    NSString *timeStr = [NSString stringWithFormat:@"%f",time];
    NSRange range1 = [timeStr rangeOfString:@"."];
    
    __block AFHTTPRequestOperation * operation;
    NSString *timeStamp = [timeStr substringToIndex:range1.location];
    NSString *idkey = serverSetting.yuLiuZiduan1;
    if (M_ISSTRNULL(idkey)) {
        idkey = @"111111";
    }
    NSString *idStr = [NSString stringWithFormat:@"%@%@",timeStamp,idkey];
    
    NSRange range ;
    range.location = 8;
    range.length = 16;
    NSString *paddword = [[@"88888888" stringFromMD5] substringWithRange:range];
    
    NSString *fileName = nil;
    NSMutableArray *imageNameArray = [NSMutableArray array];
    NSMutableArray *operationArray = [NSMutableArray array];
    for (int i = 0; i < self.imageArray.count; i ++) {
        UIImage *image = self.imageArray[i];
        NSData *imgData = UIImageJPEGRepresentation(image, 0.5f);
        fileName = [NSString stringWithFormat:@"%@___%@___%zd.jpg",contact.UserID,timeStamp,i];
        NSDictionary *dict = @{@"url":fileName};
        [imageNameArray addObject:dict];
        NSString *urlStr =[NSString stringWithFormat:@"http://%@:%zd/imconsole/mobileFile_fileUpload.action?userName=%@&password=%@&companyId=%@&type=%@&filename=%@&userId=%@&from=ios&uploadType=circle", serverSetting.IMIp, serverSetting.IMPort, @"admin", paddword, M_STOREVALUE(serverSetting.companyId), @"image", fileName, contact.UserID];
        NSString * requestUrl = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",requestUrl);
    
        AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
        NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:requestUrl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
            [formData appendPartWithFileData:imgData name:fileName fileName:fileName mimeType:@"image"];
        } error:nil];
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.responseSerializer = [AFJSONResponseSerializer serializer];
        
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (![responseObject[@"result"] isEqualToString:@"success"]) {
                [operation cancel];
             }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            //            failureHandle(operation,error);
        }];
        [operationArray addObject:operation];
    }
    
    
    
    
    
    NSDictionary *dict1 = @{@"companyId":M_STOREVALUE(serverSetting.companyId),@"userName":M_STOREVALUE(contact.UserName),@"userId":M_STOREVALUE(contact.UserID),@"type":type,@"content":M_STOREVALUE(self.contentText),@"imageName":imageNameArray,@"visibleUserId":@"all",@"id":@(idStr.longLongValue)};
    NSString *str1 = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict1 options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    NSDictionary *dict2 = @{@"key":@"efeng",@"text":str1};
    NSString *str2 = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:dict2 options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    
    NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];
    NSCalendar *canlendar = [NSCalendar currentCalendar];
    canlendar.locale = [NSLocale currentLocale];
    canlendar.timeZone = [NSTimeZone systemTimeZone];
    NSDateComponents *cmp = [canlendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:curDate];
    
    NSString *key = [NSString stringWithFormat:@"%zd%02zdwanzhaotech",cmp.year,cmp.month];
    NSString *strKey = [str2 DESEncryptWithKey:key];
    
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@:%zd/imconsole/circleContent_addReleaseContent.action?param=%@", M_STOREVALUE(serverSetting.IMIp),serverSetting.IMPort,strKey];
    NSString * requestUrl = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    NSMutableURLRequest *request = [serializer requestWithMethod:@"GET" URLString:requestUrl parameters:nil error:nil];
    operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
      [weakself didSelectCancel];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    [operationArray addObject:operation];
    
    for (int i = 0; i < operationArray.count; i ++) {
        AFHTTPRequestOperation *op = operationArray[i];
        if (i > 0) {
            AFHTTPRequestOperation *old = operationArray[i-1];
            [op addDependency:old];
        }
    }
    NSOperationQueue *quee = [[NSOperationQueue alloc] init];
    for (AFHTTPRequestOperation *op in operationArray) {
        [quee addOperation:op];
    }
    

}

@end
